<template>
  <div>
    <el-card class="search_card_user">
      <el-form class="search_form_user" :inline="true">
        <el-form-item label="用户名">
          <el-input placeholder="请输入搜索的用户名" v-model="keyword" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword.trim()" @click="search">
            搜索
          </el-button>
          <el-button type="info" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" icon="Plus" @click="addUser">
        添加用户
      </el-button>
      <el-button
        type="danger"
        icon="Delete"
        :disabled="!userIdArr.length"
        @click="batchDelete"
      >
        批量删除用户
      </el-button>
      <el-table
        class="show_table_user"
        v-if="userArr.length > 0"
        border
        stripe
        :data="userArr"
        @selection-change="selectChange"
      >
        <el-table-column align="center" type="selection" width="70" />
        <el-table-column label="#" align="center" type="index" width="70" />
        <el-table-column label="id" align="center" prop="id" width="70" />
        <el-table-column
          label="用户名字"
          align="center"
          prop="username"
          show-overflow-tooltip
        />
        <el-table-column
          label="用户昵称"
          align="center"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        />
        <el-table-column label="操作" align="center" width="320">
          <template #default="{ row }">
            <el-button type="success" icon="User" @click="assignRole(row)">
              分配角色
            </el-button>
            <el-button type="warning" icon="Edit" @click="editUser(row)">
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除当前用户吗？"
              @confirm="deleteUser(row)"
              width="200"
            >
              <template #reference>
                <el-button type="danger" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else />
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :size="'default'"
        :disabled="!(userArr.length > 0)"
        :background="true"
        layout="prev, pager, next, jumper, ->, total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-drawer v-model="isShowDrawer" direction="rtl">
      <template #header>
        <h4>{{ userParams.id ? '编辑用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <div>
          <el-form :model="userParams" :rules="userRules" ref="formRef">
            <el-form-item label="用户名字" prop="username">
              <el-input
                placeholder="请输入用户名字"
                v-model="userParams.username"
              />
            </el-form-item>
            <el-form-item label="用户昵称" prop="name">
              <el-input
                placeholder="请输入用户昵称"
                v-model="userParams.name"
              />
            </el-form-item>
            <el-form-item
              label="用户密码"
              prop="password"
              v-if="!userParams.id"
            >
              <el-input
                placeholder="请输入用户密码"
                v-model="userParams.password"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" @click="cancelClick">取消</el-button>
          <el-button type="success" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色的抽屉 -->
    <el-drawer v-model="drawer2" direction="rtl" size="30%">
      <template #header>
        <h4>分配用户角色</h4>
      </template>
      <template #default>
        <div>
          <el-form>
            <el-form-item label="用户姓名">
              <el-input disabled v-model="userParams.username" />
            </el-form-item>
            <el-form-item label="角色列表">
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                全选
              </el-checkbox>
              <el-checkbox-group
                v-model="checkedRole"
                @change="handleCheckedRolesChange"
              >
                <el-checkbox
                  v-for="item in allRole"
                  :key="item.id"
                  :label="item"
                  :value="item"
                >
                  {{ item.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" @click="cancel2">取消</el-button>
          <el-button type="primary" @click="confirm2">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
// 引入接口
import {
  reqGetUserList,
  reqAddOrUpdateUser,
  reqAllRole,
  reqAssignRole,
  reqDeleteUser,
  reqBatchDeleteUsers,
} from '@/api/acl/user'
// 引入类型
import type {
  AllRole,
  RoleListResponseData,
  UserInfo,
  UserListResponseData,
  AssignRoleData,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'

// 定义响应式数据，收集搜索关键字
let keyword = ref<string>('')
// 定义当前页
let currentPage = ref<number>(1)
// 定义每页显示多少条数据
let pageSize = ref<number>(5)
// 定义数据总数
let total = ref<number>(0)
// 定义用户数据列表
let userArr = ref<UserInfo[]>([])
// 定义 添加 / 修改 用户的抽屉组件是否展示
let isShowDrawer = ref<boolean>(false)
// 定义 分配角色 抽屉组件是否展示
let drawer2 = ref<boolean>(false)
// 定义分配角色时角色是否全选的响应式
let checkAll = ref<boolean>(false)
const isIndeterminate = ref<boolean>(false)
// 定义分配角色时选中的角色的响应式
let checkedRole = ref<AllRole>([])
// 定义全部的角色数据
let allRole = ref<AllRole>([])
// 收集用户信息的响应式数据
let userParams = reactive<UserInfo>({
  username: '',
  password: '',
  name: '',
})
// 获取 form 组件实例
let formRef = ref<any>()
// 定义收集多选用户的响应式数据
let userIdArr = ref<any[]>([])

// 页面挂载完成获取数据
onMounted(() => {
  getUserList()
})

// 获取用户列表数据
const getUserList = async (page = 1) => {
  currentPage.value = page
  let result: UserListResponseData = await reqGetUserList(
    currentPage.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code === 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}

// 搜索按钮的回调
const search = () => {
  getUserList()
  // 清空搜索框中的关键字
  keyword.value = ''
}

// 重置按钮的回调
const resetSearch = () => {
  keyword.value = ''
  getUserList()
}

// 添加用户
const addUser = () => {
  userParams.username = ''
  userParams.password = ''
  userParams.name = ''
  userParams.id = ''
  // 清空之前错误校验信息
  nextTick(() => {
    if (formRef.value && formRef.value.clearValidate) {
      formRef.value.clearValidate('username')
      formRef.value.clearValidate('name')
      formRef.value.clearValidate('password')
    }
  })
  isShowDrawer.value = true
}

// 修改用户
const editUser = (row: UserInfo) => {
  // 收集已有的用户信息
  userParams.id = row.id
  userParams.username = row.username
  userParams.name = row.name
  // 清空之前错误校验信息
  nextTick(() => {
    if (userParams.id && formRef.value && formRef.value.clearValidate) {
      formRef.value.clearValidate('username')
      formRef.value.clearValidate('name')
    }
  })
  isShowDrawer.value = true
}

// 删除用户
const deleteUser = async (row: UserInfo) => {
  let result = await reqDeleteUser(row.id)
  if (result.code === 200) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error('删除失败')
  }
  await getUserList(
    userArr.value.length > 0 ? currentPage.value : currentPage.value - 1,
  )
}

// table 复选框勾选的时候触发的事件
const selectChange = (value: any) => {
  userIdArr.value = value
}

// 批量删除的回调
const batchDelete = async () => {
  // 整理批量删除的参数
  let idList: any = (userIdArr.value = userIdArr.value.map((item: any) => {
    return item.id
  }))
  let result = await reqBatchDeleteUsers(idList)
  if (result.code === 200) {
    ElMessage.success('批量删除成功')
  } else {
    ElMessage.error('批量删除失败')
  }
  await getUserList(
    userArr.value.length > 0 ? currentPage.value : currentPage.value - 1,
  )
}

// 分配角色按钮的回调
const assignRole = async (row: UserInfo) => {
  userParams.username = row.username
  userParams.id = row.id
  // 获取所有的的角色列表与该用户所属的角色列表
  let result: RoleListResponseData = await reqAllRole(row.id)
  if (result.code === 200) {
    allRole.value = result.data.allRolesList
    checkedRole.value = result.data.assignRoles
  }
  drawer2.value = true
}

// 全选复选框的 change 事件
const handleCheckAllChange = (val: boolean) => {
  checkedRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}

// 角色复选框的 change 事件
const handleCheckedRolesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length
}

// 验证用户名字
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('用户名字不能少于两个字符'))
  }
}
// 验证用户昵称
const validatorName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('用户昵称不能少于两个字符'))
  }
}
// 验证用户密码
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('用户密码不能少于6个字符'))
  }
}
// 表单校验的规则对象
const userRules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

// 监听抽屉组件的关闭事件
const cancelClick = () => {
  isShowDrawer.value = false
}

// 监听抽屉组件的确定事件
const confirmClick = async () => {
  // 点击保存按钮先进行表单的验证，全部验证通过才可以
  await formRef.value.validate()
  let result = await reqAddOrUpdateUser(userParams)
  if (result.code === 200) {
    ElMessage.success(userParams.id ? '修改成功' : '添加成功')
  } else {
    ElMessage.error(userParams.id ? '修改失败' : '添加失败')
  }
  isShowDrawer.value = false
  await getUserList(userParams.id ? currentPage.value : 1)
  // 浏览器自动刷新一次。防止用户修改自己的信息后，获取不到修改之后的最新用户信息
  window.location.reload()
}

// 分配角色抽屉的关闭时间
const cancel2 = () => {
  drawer2.value = false
}
// 分配角色抽屉的确定事件
const confirm2 = async () => {
  // 收集数据
  let assignRoleData: AssignRoleData = {
    userId: userParams.id,
    roleIdList: checkedRole.value.map((item) => item.id),
  }
  // 分配角色
  let result = await reqAssignRole(assignRoleData)
  if (result.code === 200) {
    ElMessage.success('分配角色成功')
  } else {
    ElMessage.error('分配角色失败')
  }
  drawer2.value = false
  await getUserList(currentPage.value)
}

// 监听每页显示多少条数据
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getUserList()
}
// 监听当前页
const handleCurrentChange = (val: number) => {
  getUserList(val)
}
</script>

<style scoped>
.search_card_user {
  margin-bottom: 10px;
}
.search_form_user {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.show_table_user {
  margin: 10px 0;
}
</style>
